class User::PictureController < ApplicationController
   before_filter :validate_ownership, :except => [:index, :list, :post_comment, :show, :get_picture]
   before_filter :validate_current_catalog
   
  def index
    list
    render :action => 'list'
  end

  # GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
  verify :method => :post, :only => [ :destroy, :create, :update ],
         :redirect_to => { :action => :list }

  def list
    @user = (session[:user_id]) ? User.find(session[:user_id]) : nil
    
    @current_catalog = Catalog.find(session[:current_catalog_id]) 
    
    @path = @current_catalog.get_path(4)
        
    # Get only the picture the current user is allowed to see.
     pictures = @current_catalog.pictures.select { |picture| picture.is_accessible?(@user_id) }
     
    # Paginate the pictures in the current catalog.
    @pictures = WillPaginate::Collection.create((params[:page] or 1).to_i, 24) do |pager|
      pager.replace( pictures[pager.offset, pager.per_page].to_a )
      
      unless pager.total_entries        
        pager.total_entries = pictures.size
      end
    end
    
  end

  def show
    @user = (session[:user_id]) ? User.find(session[:user_id]) : nil
    @picture = Picture.find(params[:id])
    
    # Paginate the comments.
    @comments = WillPaginate::Collection.create((params[:page] or 1).to_i, 10) do |pager|
      pager.replace( @picture.comments[pager.offset, pager.per_page].to_a )
      
      unless pager.total_entries        
        pager.total_entries = @picture.comments.size
      end
    end
    
  end

  def new     
    @picture = Picture.new
    @picture.access = 0 # The default access is Private.      

    #puts "Current Catalog: #{@current_catalog.name}"
  end

  def create
    @picture = Picture.new(params[:picture])
    
    @current_catalog = Catalog.find(session[:current_catalog_id])   
    @picture.catalog = @current_catalog    
        
    if @picture.save      
      info('Picture was successfully created.', :notice)      
      redirect_to :action => 'list'
    else
      render :action => 'new'
    end
  end

  def edit
    @picture = Picture.find(params[:id])
  end

  def update
    @picture = Picture.find(params[:id])
    if @picture.update_attributes(params[:picture])
      @picture.fix_access()
      info("Picture was successfully updated.", :notice)      
      redirect_to :action => 'show', :id => @picture
    else
      render :action => 'edit'
    end
  end

  def destroy
    Picture.find(params[:id]).destroy
    redirect_to :action => 'list'
  end  
  
  def post_comment   
    comment = Comment.new(params[:comment])
    comment.user = User.find(session[:user_id])
    comment.picture = Picture.find(params[:id])
    
    if( comment.save )
      info("Comment added successfully", :notice)
      redirect_to(:action => 'show', :id => params[:id])
    else
      render('show')
    end
  end
  
end
